<template>
  <div style="border: 1px solid #ccc">
    <!-- wangEditor结构 -->
    <Toolbar
      v-if="showToolbarFlag"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
      style="border-bottom: 1px solid #ccc"
    />
    <Editor
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
      :style="{ height: editorHeight, overflowY: 'hidden' }"
      :readOnly="readOnlyFlag"
      class="editor"
    />
  </div>
</template>

<script setup>
import {
  shallowRef,
  ref,
  defineEmits,
  defineProps,
  nextTick,
  watch,
  onBeforeUnmount
} from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
// import * as pdfjsLib from 'pdfjs-dist'

import { uploadImageFn } from '@/api/content/addContent.js'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Boot } from '@wangeditor/editor'
import attachmentModule from '@wangeditor/plugin-upload-attachment'
if (!window._hasRegisteredAttachmentModule) {
  Boot.registerModule(attachmentModule)
  window._hasRegisteredAttachmentModule = true
}

// 定义 props
const props = defineProps({
  modelValue: { type: String, default: '' },
  showToolbarFlag: { type: Boolean, default: true },
  editorHeight: { type: String, default: '300px' },
  readOnlyFlag: { type: Boolean, default: false }
})

// 定义 emits
const emit = defineEmits()

// 编辑器实例
const editorRef = shallowRef()
const valueHtml = ref(props.modelValue)
// 配置
const mode = ref('default')
// 配置菜单栏
const toolbarConfig = {
  insertKeys: {
    index: 0,
    keys: ['uploadAttachment'] // 确保这里添加了 uploadAttachment
  },
  excludeKeys: ['fullScreen', 'insertImage', 'insertVideo']
}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {}
}

// 上传图片配置
editorConfig.MENU_CONF.uploadImage = {
  server: '',
  fieldName: 'file',
  customUpload: (result, insertFn) => {
    // 弹出确认框
    ElMessageBox.confirm('您选择了一张图片，是否确认上传？', '确认上传', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        uploadImage(result, insertFn)
      })
      .catch(() => {
        ElMessage.info('已取消上传')
      })
  }
}
// 上传视频
editorConfig.MENU_CONF.uploadVideo = {
  server: '', // 服务器上传地址
  fieldName: 'file', // 上传的字段名
  customUpload: (result, insertFn) => {
    // 弹出确认框
    ElMessageBox.confirm('您选择了一段视频，是否确认上传？', '确认上传', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        uploadVideo(result, insertFn)
      })
      .catch(() => {
        ElMessage.info('已取消上传')
      })
  }
}
// 上传附件
editorConfig.MENU_CONF.uploadAttachment = {
  server: '', // 服务器上传地址
  fieldName: 'file', // 上传的字段名
  customUpload: (result, insertFn) => {
    console.log(insertFn)
    // 弹出确认框
    ElMessageBox.confirm('您选择了pdf文件，是否确认上传？', '确认上传', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        uploadAttachment(result, insertFn)
      })
      .catch(() => {
        ElMessage.info('已取消上传')
      })
  }
}

// const uploadAttachment = async (file, insertFn) => {
//   try {
//     const formData = new FormData()
//     formData.append('file', file)
//     console.log('file', file)
//     const response = await uploadImageFn(formData)
//     // 上传成功后，将图片插入到编辑器
//     if (response.success) {
//       const url = process.env.VUE_APP_BASE_API + '/images/' + `${response.data}`
//       console.log(url)
//       insertFn(`<a href="${url}" target="_self">${file.name}</a>`)
//       ElMessage.success(response.message)
//     } else {
//       ElMessage.error('pdf上传失败')
//     }
//   } catch (error) {
//     ElMessage.error('pdf文件上传失败')
//   }
// }
const uploadAttachment = async (file, insertFn) => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    console.log('file', file)

    const response = await uploadImageFn(formData)

    // 上传成功后，将文件链接插入到编辑器
    if (response.success) {
      const url = process.env.VUE_APP_BASE_API + '/images/' + `${response.data}`
      console.log(url)

      // 插入文件链接到富文本编辑器
      // 如果希望用户下载文件，可以添加 download 属性
      // const imgData = await pdfToImage(url)
      // insertFn(imgData)

      ElMessage.success(response.message)
    } else {
      ElMessage.error('文件上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('文件上传失败')
  }
}
// 上传图片的方法
const uploadImage = async (file, insertFn) => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    const response = await uploadImageFn(formData)
    // 上传成功后，将图片插入到编辑器
    if (response.success) {
      const url = process.env.VUE_APP_BASE_API + '/images/' + `${response.data}`
      console.log(url)
      insertFn(url)

      ElMessage.success(response.message)
      // // insertFn('data:image/png;base64,' + res.data)
      // // const blob = new Blob([res.data], { type: 'image/png' })
      // // const url = window.URL.createObjectURL(blob)
      // // // 将 Base64 转换为二进制
      // const binaryString = atob(res.data)
      // const len = binaryString.length
      // const uint8Array = new Uint8Array(len)
      // for (let i = 0; i < len; i++) {
      //   uint8Array[i] = binaryString.charCodeAt(i)
      // }
      // // 创建 Blob 对象
      // const blob = new Blob([uint8Array], { type: 'image/png' })
      // // 创建 Object URL
      // const url = window.URL.createObjectURL(blob)
      // insertFn(url)
    } else {
      ElMessage.error('图片上传失败')
    }
  } catch (error) {
    ElMessage.error('图片上传失败')
  }
}
// 上传视频
const uploadVideo = async (file, insertFn) => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    console.log('file', file)
    const response = await uploadImageFn(formData)
    // 上传成功后，将图片插入到编辑器
    if (response.success) {
      const url = process.env.VUE_APP_BASE_API + '/images/' + `${response.data}`
      console.log(url)
      insertFn(url)
      ElMessage.success(response.message)
    } else {
      ElMessage.error('视频上传失败')
    }
  } catch (error) {
    ElMessage.error('视频上传失败')
  }
}
// // 将 PDF 转换为图片
// async function pdfToImage(pdfUrl) {
//   const loadingTask = pdfjsLib.getDocument(pdfUrl)
//   const pdf = await loadingTask.promise
//   const page = await pdf.getPage(1) // 获取第一页
//   const scale = 1.5 // 缩放比例
//   const viewport = page.getViewport({ scale })
//   const canvas = document.createElement('canvas')
//   const context = canvas.getContext('2d')
//   canvas.height = viewport.height
//   canvas.width = viewport.width
//   const renderContext = {
//     canvasContext: context,
//     viewport: viewport
//   }
//   await page.render(renderContext).promise
//   return canvas.toDataURL('image/png') // 返回图片的 Base64 数据
// }

// 编辑器创建时的回调
const handleCreated = (editor) => {
  editorRef.value = editor
  if (props.readOnlyFlag) {
    editorRef.value.disable()
  } else {
    editorRef.value.enable()
  }
}

// 编辑器内容变化时的回调
const handleChange = (value) => {
  valueHtml.value = editorRef.value.getHtml()
  emit('update:modelValue', valueHtml.value)
}
// 监听 props.content 的变化
watch(
  () => props.modelValue,
  (newVal) => {
    nextTick(() => {
      if (editorRef.value) {
        editorRef.value.setHtml(newVal)
        valueHtml.value = newVal
      }
    })
  },
  {
    deep: true,
    immediate: true
  }
)

// 组件销毁时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor) {
    editor.destroy()
  }
})
</script>

<style lang="scss">
.editor {
  .w-e-textarea-video-container {
    video {
      width: 100%;
    }
  }
}
</style>
